﻿using Quartz;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Common.Logging;
using Infrastructure.Lib.Core;

namespace Capture.Wholeally.Job
{
    public class WholeallyCaptureJob : IJob
    {
        private static readonly ILog logger = LogManager.GetLogger<WholeallyCaptureJob>();

        private HttpHelper httpImageCapture = new HttpHelper(ConfigurationInfo.Instatnce.BaseUrl);

        public void Execute(IJobExecutionContext context)
        {

            try
            {
                foreach (var site in ConfigurationInfo.Instatnce.Sites)
                {
                    var result = httpImageCapture.Post(new
                        {
                            device_serial = site.DeviceSerial, account = ConfigurationInfo.Instatnce.Account,
                            chan_no = Convert.ToInt32(site.ChanNo)
                        }
                        , new Dictionary<string, string>()
                        {
                            {"Accept", "application/json"},
                            {"Authorization", ConfigurationInfo.Instatnce.Authorization}
                        }
                        , ConfigurationInfo.Instatnce.ShotUrl);

                    var obj = result.JsonToModels<dynamic>();


                    if ((int) obj.ret == 0)
                    {
                        var filePath = Path.Combine(ConfigurationInfo.Instatnce.SaveImagePath, site.Id,
                            DateTime.Now.ToString(@"yyyy\\MM\\dd"));

                        if (!FileHelper.IsExistDirectory(filePath)) FileHelper.CreateDirectory(filePath);

                        Base64Helper.Base64SaveToJpeg(Convert.ToString(obj.base64_img),
                            Path.Combine(filePath, DateTime.Now.ToString("yyyyMMddhhmmss")));

                        logger.Info("save success: " + filePath);
                    }
                }
            }
            catch (Exception e)
            {
                logger.Error(e.Message);
            }
        }
    }
}
